<template>
  <div
    id="main"
    class="p-4 uni-shadow rounded-md"
  >
    <div class="p-2">
      <ElMention
        placeholder="搜索"
        v-model="searchText"
      >
        <template #prefix>
          <OhVueIcon name="io-search"></OhVueIcon>
        </template>
        <template #append>
          <div @click="onClickCreateArticle">
            <OhVueIcon
              name="ri-edit-2-line"
              class="add-button"
            ></OhVueIcon>
          </div>
        </template>
      </ElMention>
    </div>

    <div
      v-if="!isLoadComplete"
      class="p-2"
    >
      <ElSkeleton :rows="8"></ElSkeleton>
    </div>

    <el-scrollbar
      v-else
      height="92%"
    >
      <div v-for="item in articleFormatList">
        <ElDivider content-position="left">
          {{
            `${item.date.getFullYear()}-${
              item.date.getMonth() + 1
            }-${item.date.getDate()}`
          }}</ElDivider
        >
        <div
          style="height: 100px"
          class="pr-2 m-2 rounded overflow-hidden"
          v-for="card in item.rows"
        >
          <UserArticleCard
            :title="card.title"
            :content="card.synopsis"
            :date="card.createTime"
            :picture="card.pictureUrl ?? '#'"
            :value="card"
            :id="card.id"
            :read-num="card.readCount ?? 0"
            @edit="editHandle"
            @export="exportHandle"
            @delete="deleteHandle"
          ></UserArticleCard>
        </div>
      </div>
    </el-scrollbar>
  </div>
</template>

<script lang="ts" setup>
import { OhVueIcon } from "oh-vue-icons";
import { ArticleQueryMode, type ArticleResponse } from "~/models/article";
import type { DataArrResponse, ResponseMsg } from "~/models/universal";
const userProfile = useUserProfile();
const searchText = ref("");
definePageMeta({
  layout: "user-layout",
});
const onClickCreateArticle = async () => {
  await navigateTo({ path: "/blog/edit0" });
};
const isLoadComplete = ref(false);
const articleResponse = await useLazyFetch<
  ResponseMsg<DataArrResponse<ArticleResponse>>
>("/api/article/queryList", {
  method: "post",
  body: {
    mode: ArticleQueryMode.AUTHORID,
    args: {
      payload: userProfile.value?.basicId,
      isSortByTime: true,
      pageNum: 0,
      pageSize: 999,
    },
  },
});
// 文章数据缓存
const articleBuffer = ref<ArticleResponse[]>([]);
const articleTotal = ref(0);
// 文章格式化列表
const articleFormatList = computed(() => {
  let result: { date: Date; rows: ArticleResponse[] }[] = [];
  articleBuffer.value.forEach((x: ArticleResponse) => {
    let tDate = new Date(x.createTime.substring(0, 10));
    // console.log(tDate);
    if (!result.some((x) => x.date.toString() == tDate.toString())) {
      result.push({
        date: tDate,
        rows: [],
      });
    }
    result.forEach((m) => {
      if (m.date.toString() == tDate.toString()) {
        if (x.title.indexOf(searchText.value) != -1) m.rows.push(x);
      }
    });
  });
  return result;
});

const editHandle = async (card: ArticleResponse) => {
  await navigateTo({ path: `/blog/edit${card.id}` });
};
const exportHandle = (card: ArticleResponse) => {
  createSimpleElNotification(false, `暂时未开通导出:${card.title}`);
};
const deleteHandle = async (card: ArticleResponse) => {
  let deleteResult = await $fetch<ResponseMsg<boolean>>("/api/article/delete", {
    method: "post",
    body: {
      mode: "",
      args: {
        payload: card.id,
      },
    },
    headers: authHeaders(),
  });

  createSimpleElNotification(!!deleteResult.status, deleteResult.msg);

  if (!deleteResult.status) {
    return;
  }
  // await nextTick();
  articleResponse.refresh();
};

watch(articleResponse.data, (val) => {
  isLoadComplete.value = true;
  articleBuffer.value = articleResponse.data.value?.data.rows || [];
  articleTotal.value = articleResponse.data.value?.data.total;
});
</script>

<style lang="scss" scoped>
#main {
  height: max(calc(100vh - clamp(30px, 5vmax, 40px) - 120px - 6rem), 600px);
  background-color: var(--bg-secondly);
}
.add-button {
  cursor: pointer;
  opacity: 0.5;

  &:hover {
    opacity: 1;
  }
}
</style>
